package com.example.clock.controller;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.example.clock.entity.User;
import com.example.clock.service.UserService;
import com.example.clock.util.DingTalkUtil;
import com.taobao.api.ApiException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;

@Controller
@RequestMapping("/dingTalk")
public class DingTalkController {

    @Resource
    UserService userService;

    @Resource
    DingTalkUtil dingTalkUtil;

    @GetMapping("/login")
    @ResponseBody
    public HashMap<String, String> dingTalkLogin(String code) throws ApiException {
        String access_token = dingTalkUtil.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
        OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
        req.setCode(code);
        OapiV2UserGetuserinfoResponse rsp = client.execute(req, access_token);
        OapiV2UserGetuserinfoResponse.UserGetByCodeResponse result = rsp.getResult();

        String name = result.getName();
        String userid = result.getUserid();
        String deviceId = result.getDeviceId();
        HashMap<String, String> map = new HashMap<>();
        map.put("userName", name);
        map.put("userid", userid);
        map.put("deviceId", deviceId);
        userService.updateUserInfo(new User(userid, name));
        return map;
    }


}
